package dao

import (
	gojson "encoding/json"
	"github.com/go-redis/redis"
	"github.com/topfreegames/pitaya/component"
	"github.com/topfreegames/pitaya/fairy/pojo"
	"github.com/topfreegames/pitaya/fairy/util"
	"github.com/topfreegames/pitaya/logger"
	"github.com/xormplus/xorm"
	"time"
)

var (
	expirationTime time.Duration
	DeleteRoleKeppTime time.Duration
)

type BaseDao struct {
	component.Base
	enginer *xorm.Engine
	redisClient *redis.Client
}

func (p *BaseDao) Init()  {
	enginer,err := util.ManagerUtil.GetDbEnginer()
	if err != nil {
		logger.Log.Errorf("BaseDao Init failed,error:%s",err.Error())
		return
	}

	p.enginer = enginer

	rdClient,err := util.ManagerUtil.GetRedisClient()
	if err != nil {
		logger.Log.Errorf("BaseDao Init failed,error:%s",err.Error())
		return
	}
	p.redisClient = rdClient
}

func (p *BaseDao) Add(data pojo.DbData) error {
	err := p.AddDb(data)
	if err != nil {
		logger.Log.Errorf("Add failed,error:%s",err.Error())
		return err
	}

	err = p.AddCache(data)
	if err != nil {
		logger.Log.Errorf("Add failed,error:%s",err.Error())
		return err
	}
	return nil
}

func (p *BaseDao) AddDb(data pojo.DbData) error {
	_,err := p.enginer.Insert(data)
	if err != nil {
		logger.Log.Errorf("AddDb failed,error:%s",err.Error())
		return err
	}
	return nil
}

func (b *BaseDao) AddCache(data pojo.DbData) error {
	if data != nil && len(data.GetDataKey()) > 0 {
		data.SetStatus(pojo.OptInsert)
		bytes,err := gojson.Marshal(data)
		if err != nil {
			logger.Log.Errorf("AddCache failed,error:%s",err.Error())
			return err
		}
		b.redisClient.Set(data.GetDataKey(),bytes,expirationTime)
	}

	return nil
}

func (p *BaseDao) Update(data pojo.DbData) error {
	_,err := p.UpdateDb(data)
	if err != nil {
		logger.Log.Errorf("Update failed,error:%s",err.Error())
		return err
	}

	err =  p.UpdateCache(data)
	if err != nil {
		logger.Log.Errorf("Update failed,error:%s",err.Error())
		return err
	}

	return nil
}

func (p *BaseDao) UpdateDb(data pojo.DbData) (int64,error) {
	r,err := p.enginer.Update(data)
	if err != nil {
		logger.Log.Errorf("Update failed,error:%s",err.Error())
		return 0,err
	}

	return r,nil
}

func (p *BaseDao) UpdateCache(data pojo.DbData) error {
	if data != nil && len(data.GetDataKey()) > 0 {
		data.SetStatus(pojo.OptUpdate)
		bytes,err := gojson.Marshal(data)
		if err != nil {
			logger.Log.Errorf("UpdateCache failed,error:%s",err.Error())
			return err
		}
		_,err = p.redisClient.Set(data.GetDataKey(),bytes,expirationTime).Result()
		if err != nil {
			logger.Log.Errorf("UpdateCache failed,error:%s",err.Error())
			return err
		}
	}

	return nil
}

func (p *BaseDao) DeleteCache(data pojo.DbData) error {
	if data != nil && len(data.GetDataKey()) > 0 {
		_,err := p.redisClient.Del(data.GetDataKey()).Result()
		if err != nil {
			logger.Log.Errorf("DeleteCache failed,error:%s",err.Error())
			return err
		}

	}

	return nil
}
